package fun.ticsmyc.rpc.server.transport.bio;

import fun.ticsmyc.rpc.Config;
import fun.ticsmyc.rpc.common.factory.ThreadPoolFactory;
import fun.ticsmyc.rpc.server.transport.RpcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * RPC服务端 ： 监听用户请求，从线程池分配线程处理用户请求
 * @author Ticsmyc
 * @date 2020-10-23 10:01
 */
@Component
public class BioRpcServer implements RpcServer{

    private ThreadPoolExecutor threadPool = ThreadPoolFactory.getInstance();
    private static final Logger logger = LoggerFactory.getLogger(BioRpcServer.class);

    @Override
    public void startServer(CompletableFuture<Void> started){
        logger.debug("服务器启动...");
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(Config.getPort());
            started.complete(null);
            while(true){
                Socket accept = serverSocket.accept();
                logger.debug("客户端连接:  {}:{}",accept.getInetAddress(),accept.getPort());
                //提交任务给线程池执行， 不阻塞监听线程
                threadPool.execute(new RequestHandler(accept, Config.getServiceProvider(),Config.getSerializer()));
            }

        } catch (IOException e) {
            logger.error("服务器启动错误");
            e.printStackTrace();
        }finally{
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            threadPool.shutdown();
        }
    }

}
